//
//  Database.m
//  iOsiris
//
//  Created by bram on 12/16/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "Database.h"


@implementation Database

//
// Create a new instance of the Database class.
//
- (id) init
{
	if ((self = [super init]))
	{
		[self initializeDatabase];
	}
	
	return self;
}

//
// Initialize the database.
//
- (void) initializeDatabase
{
	// Get the database from the application bundle.
	NSString *path = [[NSBundle mainBundle] pathForResource:@"iosiris" ofType:@"db"];
	
	if (sqlite3_open([path UTF8String], &database) == SQLITE_OK)
	{
		NSLog(@"Opening database");
	}
	else 
	{
		// Close database properly to clean up.
		sqlite3_close(database);
		
		NSAssert1(0, @"Failed to open database: '%s'.", sqlite3_errmsg(database));
	}
}

//
// Close the database.
//
- (void) closeDatabase
{
	// Close the database.
	if (sqlite3_close(database) != SQLITE_OK) 
	{
		NSAssert1(0, @"Error: failed to close database: '%s'.", sqlite3_errmsg(database));
	}
}

- (Account*) getAccountByName:(NSString *)name
{
	// The SQL statement
	NSString *sql = [[NSString alloc] initWithFormat: @"SELECT * FROM Accounts WHERE username = '%@'", name];
	Account *account = [[Account alloc] init];
	
	sqlite3_stmt *statement; // Result
	
	// Prepare the statement.
	int sqlResult = sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL);
	
	if (sqlResult == SQLITE_OK) 
	{
		if (sqlite3_step(statement) == SQLITE_ROW)
		{
			char* username = (char*)sqlite3_column_text(statement, 1);
			char* password = (char*)sqlite3_column_text(statement, 2);
			char* study = (char*)sqlite3_column_text(statement, 6);
			
			account.userid = sqlite3_column_int(statement, 0);
			account.username = (username) ? [NSString stringWithUTF8String:username] : @"";
			account.password = (password) ? [NSString stringWithUTF8String:password] : @"";
			account.startYear = sqlite3_column_int(statement, 3);
			account.currentYear = sqlite3_column_int(statement, 4);
			account.currentPeriod = sqlite3_column_int(statement, 5);
			account.study = (study) ? [NSString stringWithUTF8String:study] : @"";
			account.fulltime = (bool)sqlite3_column_int(statement, 7);
			account.isStudent = (bool)sqlite3_column_int(statement, 7);
		}
	}
	
	// Finalise the statement to release its resources.
	sqlite3_finalize(statement);
	// Release the query string.
	[sql release];
	
	return account;
}

@end
